﻿using MultiDAQ_Analysis.Calculation.Factory;
using MultiDAQ_Analysis.Calculation.Interfaces;
using MultiDAQ_Analysis.Calculation.Parameters;
using MultiDAQ_Analysis.Calculation.Results;
using MultiDAQ_Analysis.Forms;
using MultiDAQ_Analysis.License;
using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Models;
using MultiDAQ_Analysis.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// 多通道放射性测量分析系统主界面
    /// 支持α/β射线的实时测量、多轮测量、多种样品类型测量等功能
    /// </summary>
    public partial class MainForm : UIForm
    {
        #region 字段定义

        // ========== 系统配置 ==========
        private int channelCount = AppConfig.ChannelCount;

        // ========== 通信组件 ==========
        public static UdpProtocolSender udpSender;
        private Util.UdpMessenger udpMessenger;
        private UltraHighPerformanceChannelParser parser;
        private HighSpeedUdpReceiver udpReceiver;
        // ===== 授权
        private bool _licenseCheckPassed = false; // 标记许可证检查是否通过

        // ========== 用户控件实例 - 各种测量功能模块 ==========
        private UcCenterView ucCenterView = new UcCenterView();
        private UcBaseMeasurement ucBaseMeasurement = new UcBaseMeasurement();
        private UcStandardSourceEfficiencyMeasurement ucStandardSource = new UcStandardSourceEfficiencyMeasurement();
        private UcEfficiencyMeasurement ucEfficiencyMeasurement = new UcEfficiencyMeasurement();
        private UcWaterSampleCheck ucWaterSampleCheck = new UcWaterSampleCheck();
        private UcBioSamoleCheck ucBioSamoleCheck = new UcBioSamoleCheck();
        private UcGasSampleCheck ucGasSampleCheck = new UcGasSampleCheck();
        private UcEnvSampleCheck ucEnvSampleCheck = new UcEnvSampleCheck();
        private UcUdpTool ucUdpTool = new UcUdpTool();

        // ========== 测量状态控制变量 ==========
        private System.Windows.Forms.Timer countdownTimer;
        private int remainingSeconds;
        private int measurementCount = 0;
        private int measurementTime = 0;

        // ========== 异步控制 ==========
        private CancellationTokenSource cancellationTokenSource;
        private bool isMeasurementRunning = false;

        // ========== 多轮测试配置常量 ==========
        private const int ROUND_PREPARATION_DELAY = 500;
        private const int ROUND_INTERVAL_DELAY = 2000;
        private const int DATA_PROCESSING_TIMEOUT = 3000;
        private const int START_COMMAND_DELAY = 100;

        // ========== 统一的测量计算管理 ==========
        private IMeasurementCalculator currentCalculator;
        private MeasurementCalculationContext calculationContext;
        private Dictionary<int, List<(double alpha, double beta)>> measurementHistory =
            new Dictionary<int, List<(double alpha, double beta)>>();
    
        private MultiRoundMeasurementData currentMultiRoundData;
        private Dictionary<int, List<RoundResult>> channelRoundResults = new Dictionary<int, List<RoundResult>>();


        // 在 MainForm.cs 类中添加字段
        private Dictionary<int, (long AlphaPoints, long BetaPoints, long DeductedPoints)> roundBaselineStats
            = new Dictionary<int, (long, long, long)>();

        /// <summary>
        /// 记录轮次开始前的基准统计数据
        /// </summary>
        /// <summary>
        /// 记录轮次开始前的基准统计数据 - 修正版本
        /// </summary>
        private void RecordRoundBaseline()
        {
            try
            {
                var allStatistics = ChannelDataManager.GetAllChannelStatistics(); // Dictionary<int, RealtimeStatisticsData>
                roundBaselineStats.Clear();

                foreach (var kvp in allStatistics)
                {
                    int channelIndex = kvp.Key;
                    var stats = kvp.Value;

                    roundBaselineStats[channelIndex] = (
                        stats.TotalAlphaPoints,
                        stats.TotalBetaPoints,
                        stats.TotalDeductedPoints
                    );
                }

                Console.WriteLine($"[基准] 已记录 {roundBaselineStats.Count} 个通道的基准数据");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[基准错误] 记录轮次基准失败: {ex.Message}");
            }
        }
        #endregion

        #region 构造函数与初始化

        public MainForm()
        {
            // 首先检查许可证，只有通过了才能继续
            if (!CheckLicenseOnStartup())
            {
                // 许可证检查失败，直接关闭主窗体
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Hide(); // 隐藏主窗体

                // 延迟退出，确保消息循环能正常处理
                this.BeginInvoke(new Action(() => {
                    Application.Exit();
                }));
                return;
            }


            // 初始化UI组件
            InitSettingsMenu();
            InitializeComponent();

            // 初始化其他组件
            InitCountdownTimer();
            SubscribeToMeasurementEvent();
            InitializeUdpSender();

            ShowPage(ucCenterView);

            // 初始化导航按钮数组
            InitializeNavigationButtons();

            // 初始化日志系统
            InitializeLogging();

        }


        #region 授权

        // 私有字段用于存储上次过期警告时间
        private DateTime _lastExpirationWarning = DateTime.MinValue;

        /// <summary>
        /// 启动时的许可证检查（这是关键方法）
        /// </summary>
        private bool CheckLicenseOnStartup()
        {
            try
            {
                // 步骤1: 初始化许可证管理器
                if (!InitializeLicenseManager())
                {
                    ShowErrorAndExit("许可证系统初始化失败，程序无法继续运行。");
                    return false;
                }

                // 步骤2: 检查许可证状态
                return HandleLicenseValidation();
            }
            catch (Exception ex)
            {
                ShowErrorAndExit($"许可证检查过程中发生严重错误: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 处理许可证验证逻辑
        /// </summary>
        private bool HandleLicenseValidation()
        {
            // 检查许可证文件是否存在
            if (!LicenseManager.LicenseFileExists())
            {
                return HandleFirstTimeActivation();
            }

            // 验证现有许可证
            bool isValid = LicenseManager.CheckCurrentLicense(out MyTimeLicense license, out string message);

            if (isValid)
            {
                // 检查许可证是否即将过期
                if (license != null && license.IsExpiringSoon(30))
                {
                    HandleExpiringSoonLicense(license, message);
                }
                else
                {
                    HandleValidLicense(license, message);
                }

                _licenseCheckPassed = true;
                return true;
            }
            else
            {
                // 根据错误消息判断具体原因
                if (message != null && message.Contains("过期"))
                {
                    return HandleExpiredLicense(message);
                }
                else
                {
                    return HandleInvalidLicense(message);
                }
            }
        }

        /// <summary>
        /// 处理首次激活
        /// </summary>
        private bool HandleFirstTimeActivation()
        {
            string deviceUID = LicenseManager.GetDeviceUID();

            string message = $"欢迎使用本软件！\n\n" +
                           $"这是您第一次运行此程序，需要激活许可证。\n\n" +
                           $"设备标识码: {deviceUID}\n\n" +
                           $"请点击'激活'输入许可证，或点击'退出'关闭程序。";

            var result = MessageBox.Show(message, "软件激活",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

            if (result == DialogResult.OK)
            {
                return ShowActivationDialog();
            }
            else
            {
                return false; // 用户选择退出
            }
        }

        /// <summary>
        /// 处理有效许可证
        /// </summary>
        private void HandleValidLicense(MyTimeLicense license, string message)
        {
            if (license?.ExpireDate.HasValue == true)
            {
                this.Text += $" - 许可证有效期至: {license.ExpireDate.Value:yyyy-MM-dd}";
            }
            else
            {
                this.Text += " - 永久许可证";
            }

            // 记录成功信息
            Console.WriteLine($"许可证验证成功: {message}");
        }

        /// <summary>
        /// 处理即将过期的许可证
        /// </summary>
        private void HandleExpiringSoonLicense(MyTimeLicense license, string message)
        {
            int remainingDays = license.GetRemainingDays();

            // 更新窗体标题
            this.Text += $" - 许可证 {remainingDays} 天后过期";

            // 显示过期提醒
            string warningMessage = $"许可证即将过期！\n\n" +
                                  $"剩余时间: {remainingDays} 天\n" +
                                  $"到期日期: {license.ExpireDate:yyyy-MM-dd}\n\n" +
                                  $"请及时联系供应商续费，以免影响软件正常使用。";

            MessageBox.Show(warningMessage, "许可证到期提醒",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);

            Console.WriteLine($"许可证即将过期: {message}");
        }

        /// <summary>
        /// 处理已过期的许可证
        /// </summary>
        private bool HandleExpiredLicense(string message)
        {
            string expiredMessage = $"许可证已过期！\n\n" +
                                  $"详细信息: {message}\n\n" +
                                  $"请联系供应商获取新的许可证，或点击'重新激活'输入新的许可证。";

            var result = MessageBox.Show(expiredMessage, "许可证过期",
                MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);

            if (result == DialogResult.Retry)
            {
                return ShowActivationDialog();
            }
            else
            {
                return false; // 用户选择退出
            }
        }

        /// <summary>
        /// 处理无效许可证
        /// </summary>
        private bool HandleInvalidLicense(string message)
        {
            string fullMessage = $"当前许可证无效: {message}\n\n" +
                               $"可能的原因:\n" +
                               $"• 许可证格式无效或损坏\n" +
                               $"• 许可证与当前设备不匹配\n" +
                               $"• 许可证被篡改\n\n" +
                               $"请点击'重新激活'输入新的许可证，或点击'退出'关闭程序。";

            var result = MessageBox.Show(fullMessage, "许可证无效",
                MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);

            if (result == DialogResult.Retry)
            {
                return ShowActivationDialog();
            }
            else
            {
                return false; // 用户选择退出
            }
        }

        /// <summary>
        /// 显示激活对话框（关键修复点）
        /// </summary>
        private bool ShowActivationDialog()
        {
            try
            {
                using (var inputForm = new View.LicenseInputForm())
                {
                    var result = inputForm.ShowDialog(this);

                    if (result == DialogResult.OK)
                    {
                        // 用户输入了许可证，尝试激活
                        return ProcessLicenseActivation(inputForm.LicenseText);
                    }
                    else
                    {
                        // 用户取消了激活
                        Console.WriteLine("用户取消了许可证激活");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorAndExit($"显示激活对话框时发生错误: {ex.Message}");
                return false;
            }
        }


        /// <summary>
        /// 处理许可证激活（最简化版本）
        /// </summary>
        private bool ProcessLicenseActivation(string licenseString)
        {
            try
            {
                // 首先验证许可证
                bool isValid = LicenseManager.ValidateLicense(licenseString, out MyTimeLicense license, out string message);

                if (isValid)
                {
                    // 验证成功，保存许可证文件
                    LicenseManager.SaveLicenseToFile(licenseString);

                    string successMessage = $"许可证激活成功！\n\n" +
                                          $"应用程序: {license?.AppName ?? "未知"}\n" +
                                          $"许可证类型: {license?.GetLicenseTypeDisplayName() ?? "未知"}\n";

                    if (license?.ExpireDate.HasValue == true)
                    {
                        var remainingDays = license.GetRemainingDays();
                        successMessage += $"有效期至: {license.ExpireDate.Value:yyyy-MM-dd}\n" +
                                        $"剩余时间: {remainingDays} 天";
                    }
                    else
                    {
                        successMessage += "有效期: 永久";
                    }

                    MessageBox.Show(successMessage, "激活成功",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 更新状态
                    HandleValidLicense(license, message);
                    _licenseCheckPassed = true;
                    return true;
                }
                else
                {
                    // 激活失败
                    return HandleActivationFailure(message);
                }
            }
            catch (Exception ex)
            {
                string errorMessage = $"处理许可证激活时发生错误: {ex.Message}";
                Console.WriteLine(errorMessage);

                // 如果是权限错误，提供解决方案
                if (ex.Message.Contains("访问被拒绝") || ex.Message.Contains("保存许可证文件失败") || ex.Message.Contains("UnauthorizedAccess"))
                {
                    string detailedError = $"许可证激活失败：{ex.Message}\n\n" +
                                         $"这是因为程序无法写入到安装目录。\n\n" +
                                         $"解决方案：\n" +
                                         $"1. 右键点击程序图标，选择\"以管理员身份运行\"\n" +
                                         $"2. 或者将程序安装到用户目录（如桌面或文档文件夹）\n" +
                                         $"3. 检查防病毒软件是否阻止了文件写入\n\n" +
                                         $"是否要重新尝试激活？";

                    var result = MessageBox.Show(detailedError, "权限不足",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (result == DialogResult.Yes)
                    {
                        return ShowActivationDialog();
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    var result = MessageBox.Show($"{errorMessage}\n\n是否要重新尝试激活？", "激活错误",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Error);

                    if (result == DialogResult.Yes)
                    {
                        return ShowActivationDialog();
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }

        /// <summary>
        /// 处理激活失败
        /// </summary>
        private bool HandleActivationFailure(string message)
        {
            string failureMessage = $"许可证激活失败: {message}\n\n" +
                                  $"请检查:\n" +
                                  $"• 许可证字符串是否完整且正确\n" +
                                  $"• 许可证是否适用于当前设备\n" +
                                  $"• 许可证是否已过期\n" +
                                  $"• 网络连接是否正常（如需在线验证）\n\n" +
                                  $"是否要重新输入许可证？";

            var result = MessageBox.Show(failureMessage, "激活失败",
                MessageBoxButtons.YesNo, MessageBoxIcon.Error);

            if (result == DialogResult.Yes)
            {
                return ShowActivationDialog();
            }
            else
            {
                Console.WriteLine("用户放弃重新激活");
                return false;
            }
        }

        /// <summary>
        /// 显示错误并退出程序
        /// </summary>
        private void ShowErrorAndExit(string errorMessage)
        {
            MessageBox.Show(errorMessage, "程序无法启动",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            Console.WriteLine($"程序退出: {errorMessage}");
        }

        /// <summary>
        /// 初始化许可证管理器
        /// </summary>
        private bool InitializeLicenseManager()
        {
            try
            {
                byte[] publicKeyData = LoadCertificateFile();

                if (publicKeyData == null)
                {
                    return false;
                }

                LicenseManager.Initialize(publicKeyData);
                return LicenseManager.IsInitialized();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化许可证管理器失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 加载证书文件（修改为更灵活的方式）
        /// </summary>
        private byte[] LoadCertificateFile()
        {
            try
            {
                // 方式1: 从嵌入资源加载（推荐方式）
                try
                {
                    // 假设你将证书文件添加为嵌入资源
                    // 在项目中右键添加 -> 现有项 -> 选择LicenseVerify.cer -> 属性设为嵌入的资源
                    //return Properties.Resources.LicenseVerify;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"从嵌入资源加载证书失败: {ex.Message}");
                }

                // 方式2: 从应用程序目录加载
                string certPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LicenseVerify.cer");
                if (File.Exists(certPath))
                {
                    return File.ReadAllBytes(certPath);
                }

                // 方式3: 从Resources子目录加载
                string certPath2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "LicenseVerify.cer");
                if (File.Exists(certPath2))
                {
                    return File.ReadAllBytes(certPath2);
                }

                // 方式4: 从配置的绝对路径加载（开发环境使用）
                string developmentPath = @"D:\C#WorkSpace\multi-daq-analysis\MultiDAQ-Analysis\MultiDAQ-Analysis\LicenseVerify.cer";
                if (File.Exists(developmentPath))
                {
                    Console.WriteLine($"使用开发环境路径加载证书: {developmentPath}");
                    return File.ReadAllBytes(developmentPath);
                }

                // 显示详细错误信息
                string searchInfo = $"找不到许可证验证证书文件!\n\n" +
                                  $"查找位置:\n" +
                                  $"1. 嵌入资源 (Properties.Resources.LicenseVerify)\n" +
                                  $"2. {certPath}\n" +
                                  $"3. {certPath2}\n" +
                                  $"4. {developmentPath}\n\n" +
                                  $"请确保 LicenseVerify.cer 文件存在于上述任一位置。\n\n" +
                                  $"推荐: 将证书文件作为嵌入资源添加到项目中。";

                MessageBox.Show(searchInfo, "证书文件未找到",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                return null;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载证书文件时发生错误: {ex.Message}", "加载错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        /// <summary>
        /// 初始化主界面（只有许可证通过后才调用）
        /// </summary>
        private void InitializeMainInterface()
        {
            try
            {
                // 在这里初始化您的主界面控件和功能
                Console.WriteLine("许可证验证通过，初始化主界面...");

                // 示例：添加一些控件或设置界面
                this.Text = "MultiDAQ Analysis"; // 设置窗体标题

                // 可以在这里添加菜单、工具栏等
                InitializeMenus();

                // 启动许可证状态监控
                StartLicenseMonitoring();

                Console.WriteLine("主界面初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化主界面时发生错误: {ex.Message}", "初始化错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 启动许可证状态监控
        /// </summary>
        private void StartLicenseMonitoring()
        {
            // 创建定时器，每10分钟检查一次许可证状态
            var licenseTimer = new System.Windows.Forms.Timer();
            licenseTimer.Interval = 10 * 60 * 1000; // 10分钟
            licenseTimer.Tick += (sender, e) =>
            {
                try
                {
                    // 检查当前许可证状态
                    bool isValid = LicenseManager.CheckCurrentLicense(out MyTimeLicense license, out string message);

                    if (!isValid)
                    {
                        licenseTimer.Stop();
                        MessageBox.Show($"许可证状态发生变化: {message}\n\n程序将关闭。",
                            "许可证状态异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.Close();
                    }
                    else if (license != null && license.IsExpiringSoon(30))
                    {
                        // 每天最多提醒一次即将过期
                        if (_lastExpirationWarning.Date < DateTime.Today)
                        {
                            var remainingDays = license.GetRemainingDays();
                            MessageBox.Show($"提醒：许可证将在 {remainingDays} 天后过期，请及时续期。",
                                "许可证即将过期", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            _lastExpirationWarning = DateTime.Now;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"许可证状态监控失败: {ex.Message}");
                }
            };
            licenseTimer.Start();
        }

        /// <summary>
        /// 初始化菜单（兼容原有和新版本的LicenseManager）
        /// </summary>
        private void InitializeMenus()
        {
            // 创建主菜单
            MenuStrip mainMenu = new MenuStrip();

            // 帮助菜单
            ToolStripMenuItem helpMenu = new ToolStripMenuItem("帮助(&H)");

            // 许可证信息菜单项
            ToolStripMenuItem licenseInfoItem = new ToolStripMenuItem("许可证信息(&L)");
            licenseInfoItem.Click += MenuItemLicenseInfo_Click;

            // 重新激活菜单项
            ToolStripMenuItem reactivateItem = new ToolStripMenuItem("重新激活(&R)");
            reactivateItem.Click += MenuItemReactivate_Click;

            // 关于菜单项
            ToolStripMenuItem aboutItem = new ToolStripMenuItem("关于(&A)");
            aboutItem.Click += MenuItemAbout_Click;

            helpMenu.DropDownItems.Add(licenseInfoItem);
            helpMenu.DropDownItems.Add(new ToolStripSeparator());
            helpMenu.DropDownItems.Add(reactivateItem);
            helpMenu.DropDownItems.Add(new ToolStripSeparator());
            helpMenu.DropDownItems.Add(aboutItem);

            mainMenu.Items.Add(helpMenu);

            this.MainMenuStrip = mainMenu;
            this.Controls.Add(mainMenu);
        }

        /// <summary>
        /// 许可证信息菜单项点击事件（简化版本）
        /// </summary>
        private void MenuItemLicenseInfo_Click(object sender, EventArgs e)
        {
            try
            {
                // 尝试使用新版本的LicenseViewForm
                try
                {
                    using (var licenseViewForm = new View.LicenseViewForm())
                    {
                        licenseViewForm.ShowDialog(this);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"新版许可证界面不可用: {ex.Message}，使用简单信息显示");
                }

                // 回退到简单的信息显示
                if (LicenseManager.CheckCurrentLicense(out MyTimeLicense license, out string message))
                {
                    string info = $"许可证信息:\n\n" +
                                $"应用程序: {license?.AppName ?? "未知"}\n" +
                                $"许可证类型: {license?.GetLicenseTypeDisplayName() ?? "未知"}\n";

                    if (license?.UID != null)
                        info += $"设备标识: {license.UID}\n";

                    if (license?.ExpireDate.HasValue == true)
                    {
                        info += $"到期时间: {license.ExpireDate.Value:yyyy-MM-dd}\n";
                        info += $"剩余天数: {license.GetRemainingDays()} 天\n";
                    }
                    else
                    {
                        info += "到期时间: 永久\n";
                    }

                    info += $"状态: {message}";

                    MessageBox.Show(info, "许可证信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("当前没有有效的许可证。", "许可证信息",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取许可证信息失败: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 重新激活菜单项点击事件
        /// </summary>
        private void MenuItemReactivate_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("确定要重新激活许可证吗？\n\n这将替换当前的许可证。", "确认重新激活",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    if (ShowActivationDialog())
                    {
                        MessageBox.Show("重新激活成功！", "成功",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 可能需要刷新主界面显示
                        if (LicenseManager.CheckCurrentLicense(out MyTimeLicense license, out string message))
                        {
                            HandleValidLicense(license, message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"重新激活过程中发生错误: {ex.Message}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 关于菜单项点击事件
        /// </summary>
        private void MenuItemAbout_Click(object sender, EventArgs e)
        {
            try
            {
                string statusText = "未知状态";
                string remainingText = "未知";

                if (LicenseManager.CheckCurrentLicense(out MyTimeLicense license, out string message))
                {
                    statusText = "许可证有效";
                    if (license?.ExpireDate.HasValue == true)
                    {
                        var remainingDays = license.GetRemainingDays();
                        remainingText = remainingDays > 0 ? $"{remainingDays} 天" : "已过期";
                    }
                    else
                    {
                        remainingText = "永久";
                    }
                }
                else
                {
                    statusText = "许可证无效";
                }

                string aboutText = $"MultiDAQ Analysis v1.0\n\n" +
                                 $"许可证状态: {statusText}\n" +
                                 $"剩余天数: {remainingText}\n\n" +
                                 $"Copyright © 2025 Your Company\n" +
                                 $"保留所有权利";

                MessageBox.Show(aboutText, "关于 MultiDAQ Analysis",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取软件信息失败: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 重写窗体关闭事件
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 如果许可证检查没有通过，直接允许关闭
            if (!_licenseCheckPassed)
            {
                base.OnFormClosing(e);
                return;
            }

            // 正常的关闭确认
            if (e.CloseReason == CloseReason.UserClosing)
            {
                var result = MessageBox.Show("确定要退出程序吗？", "确认退出",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }

            base.OnFormClosing(e);
        }

        /// <summary>
        /// 重写SetVisibleCore确保在许可证检查前不显示主窗体
        /// </summary>
        protected override void SetVisibleCore(bool value)
        {
            // 如果许可证检查还没通过，不显示主窗体
            if (!_licenseCheckPassed && value)
            {
                base.SetVisibleCore(false);
                return;
            }

            base.SetVisibleCore(value);
        }
        #endregion


        /// <summary>
        /// 初始化导航按钮数组
        /// </summary>
        private void InitializeNavigationButtons()
        {
            navButtons = new UIButton[] {
                btnBackground, btnWorkingSource, btnStandardSource,
                btnWaterSample, btnBioSample, btnGasSample, btnEnvSample, btnStopMeasurement
            };
        }

        private void InitializeLogging()
        {
            try
            {
                // 1) 首选：当前用户本地应用数据
                string baseDir = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    "Yuanbao", "Logs");

                // 如果需要机器级日志，改用：
                // string baseDir = Path.Combine(
                //     Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                //     "Yuanbao", "Logs");

                // 2) 确保目录存在
                Directory.CreateDirectory(baseDir);

                // 3) 日志文件名（按日切分）
                string logPath = Path.Combine(baseDir, $"app_{DateTime.Now:yyyyMMdd}.log");

                // 4) 初始化你的日志写入（示例：GlobalConsoleCapture）
                GlobalConsoleCapture.Initialize(logPath);
                Console.WriteLine($"[系统] 启动时间: {DateTime.Now}");
            }
            catch (UnauthorizedAccessException uex)
            {
                // 权限不足时，兜底到临时目录
                try
                {
                    string tempDir = Path.Combine(Path.GetTempPath(), "Yuanbao", "Logs");
                    Directory.CreateDirectory(tempDir);
                    string tempLogPath = Path.Combine(tempDir, $"app_{DateTime.Now:yyyyMMdd}.log");

                    GlobalConsoleCapture.Initialize(tempLogPath);
                    Console.WriteLine($"[系统] 启动（降级到临时目录）: {DateTime.Now}，原因：{uex.Message}");
                }
                catch (Exception ex2)
                {
                    CompactMessageBox.ShowError($"日志系统初始化失败（权限）：{uex.Message}\n兜底也失败：{ex2.Message}");
                }
            }
            catch (DirectoryNotFoundException dex)
            {
                // 路径不存在/介质路径异常（例如从只读介质运行安装程序）
                try
                {
                    string tempDir = Path.Combine(Path.GetTempPath(), "Yuanbao", "Logs");
                    Directory.CreateDirectory(tempDir);
                    string tempLogPath = Path.Combine(tempDir, $"app_{DateTime.Now:yyyyMMdd}.log");

                    GlobalConsoleCapture.Initialize(tempLogPath);
                    Console.WriteLine($"[系统] 启动（目录兜底）: {DateTime.Now}，原因：{dex.Message}");
                }
                catch (Exception ex2)
                {
                    CompactMessageBox.ShowError($"日志系统初始化失败（目录）：{dex.Message}\n兜底也失败：{ex2.Message}");
                }
            }
            catch (Exception ex)
            {
                CompactMessageBox.ShowError($"日志系统初始化失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 初始化UDP发送器
        /// </summary>
        private void InitializeUdpSender()
        {
            try
            {
                udpSender = new UdpProtocolSender();
                udpSender.OnLogMessage += msg => Console.WriteLine($"[发送] {msg}");
                udpSender.OnErrorMessage += err => Console.WriteLine($"[发送错误] {err}");
            }
            catch (Exception ex)
            {
                CompactMessageBox.ShowError($"UDP发送器初始化失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化倒计时定时器
        /// </summary>
        private void InitCountdownTimer()
        {
            countdownTimer = new System.Windows.Forms.Timer
            {
                Interval = 1000 // 每秒更新一次
            };
            countdownTimer.Tick += CountdownTimer_Tick;
        }

        /// <summary>
        /// 订阅所有测量控件的测量开始事件
        /// </summary>
        private void SubscribeToMeasurementEvent()
        {
            ucBaseMeasurement.OnMeasurementStarted += HandleMeasurementStarted;
            ucBioSamoleCheck.OnMeasurementStarted += HandleMeasurementStarted;
            ucEfficiencyMeasurement.OnMeasurementStarted += HandleMeasurementStarted;
            ucEnvSampleCheck.OnMeasurementStarted += HandleMeasurementStarted;
            ucGasSampleCheck.OnMeasurementStarted += HandleMeasurementStarted;
            ucStandardSource.OnMeasurementStarted += HandleMeasurementStarted;
            ucWaterSampleCheck.OnMeasurementStarted += HandleMeasurementStarted;
        }

        #endregion

        #region 设置菜单相关

        /// <summary>
        /// 初始化设置上下文菜单
        /// </summary>
        private void InitSettingsMenu()
        {
            settingsContextMenu = new UIContextMenuStrip
            {
                ShowImageMargin = false,
                Font = new Font("微软雅黑", 9F),
                BackColor = Color.White,
                ForeColor = Color.Black,
                AutoClose = true,
                Padding = Padding.Empty
            };

            itemDeviceSetting = new ToolStripMenuItem("仪器参数");
            itemWorkCondition = new ToolStripMenuItem("工作条件");
            itemDACSetting = new ToolStripMenuItem("DAC设置");

            // 设置菜单项样式
            ConfigureMenuItem(itemDeviceSetting);
            ConfigureMenuItem(itemWorkCondition);
            ConfigureMenuItem(itemDACSetting);

            // 添加到菜单
            settingsContextMenu.Items.AddRange(new ToolStripItem[] {
                itemDeviceSetting,
                itemWorkCondition,
                itemDACSetting
            });

            // 绑定事件
            itemDeviceSetting.Click += ItemDeviceSetting_Click;
            itemWorkCondition.Click += ItemWorkCondition_Click;
            itemDACSetting.Click += btnDACSettings_Click;
        }

        /// <summary>
        /// 配置菜单项样式
        /// </summary>
        private void ConfigureMenuItem(ToolStripMenuItem item)
        {
            item.AutoSize = false;
            item.TextAlign = ContentAlignment.MiddleLeft;
            item.Font = new Font("微软雅黑", 8.5F);
            item.Padding = new Padding(5, 2, 5, 2);
            item.Size = new Size(100, 28);
        }

        private void MenuItemSettings_Click(object sender, EventArgs e)
        {
            var menuItemBounds = menuItemSettings.Bounds;
            Point popupLocation = menuStrip.PointToScreen(new Point(menuItemBounds.Left, menuItemBounds.Bottom));
            settingsContextMenu.Show(popupLocation);
        }

        private void ItemDeviceSetting_Click(object sender, EventArgs e)
        {
            new DeviceSettingsForm().ShowDialog();
        }

        private void ItemWorkCondition_Click(object sender, EventArgs e)
        {
            new WorkConditionForm().ShowDialog();
        }
        private void btnDACSettings_Click(object sender, EventArgs e)
        {
            ShowDACSettingsDialog();
        }

        /// <summary>
        /// 显示DAC设置对话框
        /// </summary>
        private void ShowDACSettingsDialog()
        {
            try
            {
                using (var dacForm = new DACSettingsForm(udpSender))
                {
                    dacForm.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                CompactMessageBox.ShowError($"打开DAC设置窗口失败: {ex.Message}");
            }
        }

        #endregion

        #region 菜单和按钮事件处理

        private void menuItemMeasurement_Click(object sender, EventArgs e)
        {
            var resultsForm = new AllChannelsMeasurementResultsForm();
            resultsForm.ShowDialog(this);
        }

        private void menuItemDebug_Click(object sender, EventArgs e)
        {
            AdcDebugForm debugForm = new AdcDebugForm();
            debugForm.ShowDialog();  // 模态显示，必须关闭调试窗口才能操作主窗口
        }

        
        // 各种测量按钮点击事件
        private void btnBackground_Click(object sender, EventArgs e)
        {
            SetSelectedButton(btnBackground);
            ucBaseMeasurement.RefreshData();
            ShowPopupForm("本底测量", ucBaseMeasurement);
        }

        private void btnStandardSource_Click(object sender, EventArgs e)
        {
            SetSelectedButton(btnStandardSource);
            ucStandardSource.RefreshData();
            ShowPopupForm("标准源效率测量", ucStandardSource);
        }

        private void btnWorkingSource_Click(object sender, EventArgs e)
        {
            SetSelectedButton(btnWorkingSource);
            ucEfficiencyMeasurement.RefreshData();
            ShowPopupForm("工作源效率测量", ucEfficiencyMeasurement);
        }

        private void btnWaterSample_Click(object sender, EventArgs e)
        {
            SetSelectedButton(btnWaterSample);
            ucWaterSampleCheck.RefreshData();
            ShowPopupForm("水样品测量", ucWaterSampleCheck);
        }

        private void btnBioSample_Click(object sender, EventArgs e)
        {
            SetSelectedButton(btnBioSample);
            ucBioSamoleCheck.RefreshData();
            ShowPopupForm("生物样品测量", ucBioSamoleCheck);
        }

        private void btnGasSample_Click(object sender, EventArgs e)
        {
            SetSelectedButton(btnGasSample);
            ucGasSampleCheck.RefreshData();
            ShowPopupForm("气体样品测量", ucGasSampleCheck);
        }

        private void btnEnvSample_Click(object sender, EventArgs e)
        {
            SetSelectedButton(btnEnvSample);
            ucEnvSampleCheck.RefreshData();
            ShowPopupForm("环境样品测量", ucEnvSampleCheck);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            ShowPopupForm("测试", ucUdpTool);
        }

        #endregion

        #region UI辅助方法

        /// <summary>
        /// 显示弹出窗口
        /// </summary>
        private void ShowPopupForm(string title, UserControl userControl)
        {
            PopupForm popupForm = new PopupForm(title, userControl);
            popupForm.ShowDialog();
        }

        /// <summary>
        /// 在主面板中显示页面
        /// </summary>
        private void ShowPage(UserControl page)
        {
            panelMainContent.Controls.Clear();
            page.Dock = DockStyle.Fill;
            panelMainContent.Controls.Add(page);
        }

        /// <summary>
        /// 设置选中的导航按钮样式
        /// </summary>
        private void SetSelectedButton(UIButton selected)
        {
            foreach (var btn in navButtons)
            {
                if (btn == selected)
                {
                    // 设置选中状态样式
                    btn.FillColor = Color.FromArgb(40, 160, 255);
                    btn.RectColor = Color.FromArgb(24, 130, 220);
                    btn.ForeColor = Color.White;
                    btn.Font = new Font(btn.Font, FontStyle.Bold);
                }
                else
                {
                    // 设置未选中状态样式
                    btn.FillColor = Color.White;
                    btn.RectColor = Color.Gainsboro;
                    btn.ForeColor = Color.Black;
                    btn.Font = new Font(btn.Font, FontStyle.Regular);
                }
            }
        }

        /// <summary>
        /// 线程安全的UI更新方法
        /// </summary>
        private void UpdateUI(Action updateAction)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(updateAction);
            }
            else
            {
                updateAction();
            }
        }

        /// <summary>
        /// 重置UI显示状态
        /// </summary>
        private void ResetUIDisplay()
        {
            UpdateUI(() => {
                lblCount.Text = "次数: 0";
                lblStatus.Text = "状态: 停止";
                lblResult.Text = "结果: 无";
                lblRemaining.Text = "";
            });
        }

        /// <summary>
        /// 更新剩余时间显示
        /// </summary>
        private void UpdateRemainingTimeDisplay(int totalSeconds)
        {
            int minutes = totalSeconds / 60;
            int seconds = totalSeconds % 60;

            if (minutes > 0)
            {
                lblRemaining.Text = $"剩余: {minutes}分{seconds}秒";
            }
            else
            {
                lblRemaining.Text = $"剩余: {seconds}秒";
            }
        }

        #endregion

        #region 按钮状态控制

        /// <summary>
        /// 设置测量相关按钮的启用状态
        /// </summary>
        private void SetMeasurementButtonsEnabled(bool enabled)
        {
            var measurementButtons = new UIButton[] {
                btnBackground, btnWorkingSource, btnStandardSource,
                btnWaterSample, btnBioSample, btnGasSample, btnEnvSample
            };

            foreach (var button in measurementButtons)
            {
                button.Enabled = enabled;
            }
        }

        /// <summary>
        /// 设置停止按钮状态
        /// </summary>
        private void SetStopButtonState(bool enabled, string text = "停止采集", Color? fillColor = null)
        {
            btnStopMeasurement.Enabled = enabled;
            btnStopMeasurement.Text = text;
            btnStopMeasurement.FillColor = fillColor ?? (enabled ? Color.FromArgb(255, 87, 87) : Color.Gray);
        }

        #endregion

        #region 倒计时功能

        /// <summary>
        /// 倒计时定时器事件处理
        /// </summary>
        private void CountdownTimer_Tick(object sender, EventArgs e)
        {
            if (remainingSeconds > 0)
            {
                remainingSeconds--;
                this.Invoke(new Action(() => UpdateRemainingTimeDisplay(remainingSeconds)));
            }
            else
            {
                countdownTimer.Stop();
            }
        }

        #endregion

        #region 测量控制核心逻辑

        /// <summary>
        /// 处理测量开始事件的主入口点
        /// </summary>
        private async void HandleMeasurementStarted(int count, int time)
        {
            try
            {
                // 初始化计算器和上下文
                InitializeCalculationSystem(count, time);

                await InitializeMeasurementSystem(count, time);
                await ExecuteMeasurementLoop(count, time);
            }
            catch (OperationCanceledException)
            {
                HandleMeasurementCancelled();
            }
            catch (Exception ex)
            {
                HandleMeasurementError(ex);
            }
            finally
            {
                await CleanupMeasurement();
            }
        }

        #region 初始化阶段

        /// <summary>
        /// 初始化计算系统
        /// </summary>
        /// <summary>
        /// 初始化计算系统 - 修改版本
        /// </summary>
        private void InitializeCalculationSystem(int count, int time)
        {
            try
            {
                string measurementType = DetermineMeasurementType();
                Console.WriteLine($"[计算系统] 检测到测量类型: {measurementType}");

                currentCalculator = MeasurementCalculatorFactory.CreateCalculator(measurementType);
                Console.WriteLine($"[计算系统] 创建计算器: {currentCalculator?.GetType().Name ?? "null"}");

                var parameters = GetMeasurementParameters(measurementType);
                if (parameters != null && !parameters.Validate())
                {
                    throw new ArgumentException($"测量参数验证失败: {measurementType}");
                }

                calculationContext = new MeasurementCalculationContext
                {
                    TotalRounds = count,
                    MeasurementTimeMinutes = time,
                    HistoryData = measurementHistory,
                    Parameters = parameters
                };

                // 初始化多轮数据存储 - 新增
                InitializeMultiRoundDataStorage(measurementType, count, time, parameters);

                InitializeMeasurementHistory();
                Console.WriteLine($"[计算系统] {measurementType} 计算系统初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[计算系统错误] 初始化失败: {ex.Message}");
                throw;
            }
        }


        /// <summary>
        /// 初始化多轮数据存储 - 新增方法
        /// </summary>
        /// <summary>
        /// 初始化多轮数据存储 - 修改版本
        /// </summary>
        private void InitializeMultiRoundDataStorage(string measurementType, int count, int time, MeasurementParameters parameters)
        {
            currentMultiRoundData = new MultiRoundMeasurementData
            {
                MeasurementType = measurementType,
                StartTime = DateTime.Now,
                TotalRounds = count,
                MeasurementTimeMinutes = time,
                Parameters = parameters
            };

            // 新增：保存计算上下文信息
            currentMultiRoundData.CalculationContext = new MeasurementCalculationContextData
            {
                TotalRounds = count,
                MeasurementTimeMinutes = time,
                CalculatorType = currentCalculator?.GetType().Name ?? "Unknown",
                Parameters = parameters,
                SelectedChannels = ChannelDataManager.GetSelectedChannels().Select(c => c.ChannelIndex).ToList(),
                ContextCreatedTime = DateTime.Now
            };

            channelRoundResults.Clear();
            var selectedChannels = ChannelDataManager.GetSelectedChannels();

            foreach (var channelData in selectedChannels)
            {
                int channelIndex = channelData.ChannelIndex;
                channelRoundResults[channelIndex] = new List<RoundResult>();

                currentMultiRoundData.ChannelResults[channelIndex] = new ChannelMultiRoundResult
                {
                    ChannelIndex = channelIndex
                };
            }

            Console.WriteLine($"[多轮存储] 初始化完成，共 {selectedChannels.Count} 个通道");
        }

        /// <summary>
        /// 处理最终结果 - 修改版本，使用按通道保存
        /// </summary>
        private async Task ProcessFinalResults()
        {
            try
            {
                Console.WriteLine("[最终处理] 开始计算平均结果");

                // 计算所有通道的平均结果和统计信息
                CalculateAverageResults();

                // 设置结束时间
                currentMultiRoundData.EndTime = DateTime.Now;

                // 保存到JSON - 使用两种方式保存
                await JsonDataManager.SaveMultiRoundDataAsync(currentMultiRoundData); // 原始方式
                await ChannelBasedJsonDataManager.SaveMultiRoundDataByChannelAsync(currentMultiRoundData); // 按通道保存

                // 创建最终的计算结果用于数据库保存
                var finalResult = CreateFinalCalculationResult();

                // 保存到数据库
                if (currentCalculator != null)
                {
                    await currentCalculator.SaveResultsAsync(finalResult);
                    Console.WriteLine("[保存] 最终结果已保存");
                }

                // 显示最终结果
                DisplayFinalResults(finalResult);

                Console.WriteLine("[最终处理] 所有结果处理完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[最终处理错误] {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 初始化测量历史数据
        /// </summary>
        private void InitializeMeasurementHistory()
        {
            measurementHistory.Clear();
            for (int i = 0; i < channelCount; i++)
            {
                measurementHistory[i] = new List<(double alpha, double beta)>();
            }
        }

        /// <summary>
        /// 确定当前测量类型
        /// </summary>
        private string DetermineMeasurementType()
        {
            var selectedButton = navButtons.FirstOrDefault(btn =>
                btn.FillColor == Color.FromArgb(40, 160, 255));

            string measurementType = MeasurementCalculatorFactory.GetMeasurementType(selectedButton);

            Console.WriteLine($"[类型检测] 选中按钮: {selectedButton?.Name ?? "null"}");
            Console.WriteLine($"[类型检测] 测量类型: {measurementType}");

            return measurementType;
        }

        /// <summary>
        /// 初始化测量系统
        /// </summary>
        private async Task InitializeMeasurementSystem(int count, int time)
        {
            Console.WriteLine("[初始化] 开始测量系统初始化");

            // 初始化基础状态
            InitializeBasicState(count, time);

            // 更新UI状态
            UpdateUI(() => {
                lblStatus.Text = "状态: 准备中";
                lblResult.Text = "结果: 初始化中";
            });

            // 初始化数据处理系统
            try
            {
                InitializeParser();
                ConfigureUdpComponents();
                await StartDataProcessingPipeline();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[初始化错误] 数据处理系统初始化失败: {ex.Message}");
                throw;
            }

            Console.WriteLine("[初始化] 测量系统初始化完成");
        }

        /// <summary>
        /// 初始化基础状态变量
        /// </summary>
        private void InitializeBasicState(int count, int time)
        {
            cancellationTokenSource = new CancellationTokenSource();
            isMeasurementRunning = true;
            measurementCount = count;
            measurementTime = time;

            SetMeasurementButtonsEnabled(false);
            SetStopButtonState(true);
        }

        /// <summary>
        /// 初始化高性能通道解析器
        /// </summary>
        private void InitializeParser()
        {
            parser = new UltraHighPerformanceChannelParser(
                minThreads: 1,
                maxThreads: Environment.ProcessorCount
            );
            parser.IsHighEndVersion = true;

            // 配置选中的通道
            var selectedChannels = ChannelDataManager.GetSelectedChannels();
            Console.WriteLine($"[配置] 共 {selectedChannels.Count} 个选中通道");

            foreach (var channel in selectedChannels)
            {
                parser.SelectedChannels[channel.ChannelIndex] = true;
            }

            // 连接到显示面板
            ucCenterView.ConnectToParser(parser);
        }

        /// <summary>
        /// 配置UDP通信组件
        /// </summary>
        private void ConfigureUdpComponents()
        {
            udpSender.OnLogMessage += msg => Console.WriteLine($"[发送] {msg}");
            udpSender.OnErrorMessage += err => Console.WriteLine($"[发送错误] {err}");
            udpReceiver = new HighSpeedUdpReceiver(parser, AppConfig.UdpListenPort);
        }

        /// <summary>
        /// 启动数据处理流水线
        /// </summary>
        private async Task StartDataProcessingPipeline()
        {
            Console.WriteLine("[启动] 数据处理流水线");

            parser.Start();
            ucCenterView.startPlotPanel(parser);
            udpReceiver.Start();

            await Task.Delay(100);
        }

        #endregion

        #region 测量执行阶段

        /// <summary>
        /// 执行测量循环
        /// </summary>
        private async Task ExecuteMeasurementLoop(int totalCount, int measurementTime)
        {
            Console.WriteLine($"[执行] 开始测量循环，共 {totalCount} 轮");

            for (int round = 1; round <= totalCount; round++)
            {
                cancellationTokenSource.Token.ThrowIfCancellationRequested();

                Console.WriteLine($"[轮次] ========== 第 {round} 轮测量开始 ==========");

                await ExecuteSingleMeasurementRound(round, totalCount, measurementTime);

                Console.WriteLine($"[轮次] ========== 第 {round} 轮测量完成 ==========");

                if (round < totalCount)
                {
                    await PrepareForNextRound(round + 1);
                }
            }

            await HandleAllRoundsCompleted(totalCount);
        }

        /// <summary>
        /// 执行单轮测量
        /// </summary>
        private async Task ExecuteSingleMeasurementRound(int currentRound, int totalCount, int measurementTime)
        {
            try
            {
                await PrepareRoundMeasurement(currentRound, totalCount);
                await StartRoundMeasurement(currentRound, measurementTime);
                await ExecuteRoundWaiting(currentRound, measurementTime);
                await CompleteRoundMeasurement(currentRound);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[轮次错误] 第 {currentRound} 轮测量失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 准备单轮测量 - 添加UDP接收器启动逻辑
        /// </summary>
        private async Task PrepareRoundMeasurement(int currentRound, int totalCount)
        {
            Console.WriteLine($"[准备] 第 {currentRound} 轮测量准备");

            UpdateUI(() => {
                lblCount.Text = $"轮次: {currentRound}/{totalCount}";
                lblStatus.Text = "状态: 准备中";
                lblResult.Text = $"准备第{currentRound}轮测量...";
                lblRemaining.Text = "";
            });

            await ResetDisplayState();

            // 记录本轮开始前的基准数据
            RecordRoundBaseline();

            // 新增：为新轮次启动UDP接收器
            await StartUdpReceiverForRound(currentRound);

            await Task.Delay(ROUND_PREPARATION_DELAY);
        }

        /// <summary>
        /// 启动单轮测量
        /// </summary>
        private async Task StartRoundMeasurement(int currentRound, int measurementTime)
        {
            Console.WriteLine($"[启动] 第 {currentRound} 轮测量启动");

            SendMeasurementStartCommand();

            remainingSeconds = measurementTime * 60;
            countdownTimer.Start();

            UpdateUI(() => {
                lblStatus.Text = "状态: 测量中";
                lblResult.Text = $"第{currentRound}轮测量进行中...";
            });

            await Task.Delay(START_COMMAND_DELAY);
        }

        /// <summary>
        /// 执行轮次等待（测量时间）
        /// </summary>
        private async Task ExecuteRoundWaiting(int currentRound, int measurementTime)
        {
            Console.WriteLine($"[等待] 第 {currentRound} 轮测量等待 {measurementTime} 分钟");
            await WaitForMeasurementCompletion(measurementTime, cancellationTokenSource.Token);
        }

        /// <summary>
        /// 完成单轮测量
        /// </summary>
        private async Task CompleteRoundMeasurement(int currentRound)
        {
            Console.WriteLine($"[完成] 第 {currentRound} 轮测量完成处理");

            countdownTimer.Stop();
            SendRoundStopCommand();

            UpdateUI(() => {
                lblStatus.Text = "状态: 轮次完成";
                lblResult.Text = $"第{currentRound}轮测量完成";
                lblRemaining.Text = "剩余: 当前轮完成";
            });
            // 新增：关闭UDP接收器，确保数据停止接收
            await StopUdpReceiverForRound(currentRound);

            await WaitForRoundDataComplete();
            await CollectMeasurementDataFromCurrentRound(currentRound);

            Console.WriteLine($"[完成] 第 {currentRound} 轮数据处理完成");
        }

        /// <summary>
        /// 为轮次停止UDP接收器
        /// </summary>
        private async Task StopUdpReceiverForRound(int currentRound)
        {
            try
            {
                Console.WriteLine($"[UDP控制] 第 {currentRound} 轮结束，停止UDP接收器");

                if (udpReceiver != null)
                {
                    udpReceiver.Stop();
                    Console.WriteLine($"[UDP控制] UDP接收器已停止");
                }

                // 给一点时间确保完全停止
                await Task.Delay(300);

                // 等待解析器处理完剩余数据
                if (parser != null)
                {
                    await WaitForParserToFinishCurrentData();
                }

                Console.WriteLine($"[UDP控制] 第 {currentRound} 轮UDP接收器关闭完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UDP控制错误] 第 {currentRound} 轮停止UDP接收器失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 为轮次启动UDP接收器
        /// </summary>
        private async Task StartUdpReceiverForRound(int currentRound)
        {
            try
            {
                Console.WriteLine($"[UDP控制] 第 {currentRound} 轮开始，启动UDP接收器");

                // 确保解析器处于就绪状态
                if (parser != null && !parser.IsRunning) // 假设有IsRunning属性
                {
                    parser.Start();
                    await Task.Delay(100);
                }

                // 重新创建UDP接收器（确保状态干净）
                if (udpReceiver != null)
                {
                    udpReceiver.Dispose();
                }

                udpReceiver = new HighSpeedUdpReceiver(parser, AppConfig.UdpListenPort);
                udpReceiver.Start();

                Console.WriteLine($"[UDP控制] 第 {currentRound} 轮UDP接收器启动完成");

                // 给一点时间确保完全启动
                await Task.Delay(200);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UDP控制错误] 第 {currentRound} 轮启动UDP接收器失败: {ex.Message}");
                throw; // 重新抛出，因为这是关键错误
            }
        }

        /// <summary>
        /// 等待解析器处理完当前数据
        /// </summary>
        private async Task WaitForParserToFinishCurrentData()
        {
            const int maxWaitTime = 1000; // 最多等1秒
            const int checkInterval = 50;
            int elapsed = 0;

            while (elapsed < maxWaitTime)
            {
                try
                {
                    var voltagePoints = parser.GetVoltagePoints();
                    await Task.Delay(checkInterval);
                    var voltagePoints2 = parser.GetVoltagePoints();

                    if (voltagePoints.Count == voltagePoints2.Count)
                    {
                        Console.WriteLine("[UDP控制] 解析器数据处理已稳定");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[UDP控制警告] 检查解析器状态异常: {ex.Message}");
                    break;
                }

                elapsed += checkInterval;
            }

            Console.WriteLine("[UDP控制警告] 解析器数据处理等待超时");
        }

        /// <summary>
        /// 准备下一轮测量
        /// </summary>
        private async Task PrepareForNextRound(int nextRound)
        {
            Console.WriteLine($"[间隔] 准备第 {nextRound} 轮测量");

            UpdateUI(() => {
                lblStatus.Text = "状态: 轮间等待";
                lblResult.Text = $"准备第{nextRound}轮...";
                lblRemaining.Text = "";
            });

            await Task.Delay(ROUND_INTERVAL_DELAY, cancellationTokenSource.Token);
        }

        /// <summary>
        /// 重置显示状态
        /// </summary>
        private async Task ResetDisplayState()
        {
            Console.WriteLine("[重置] 重置显示状态");

            try
            {
                if (ucCenterView != null)
                {
                    UpdateUI(() => ucCenterView.StopPlotPanel());
                    await Task.Delay(200);
                    UpdateUI(() => ucCenterView.startPlotPanel(parser));
                    Console.WriteLine("[重置] 显示面板已重置");
                }

                await Task.Delay(300);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[重置错误] 显示状态重置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 发送测量启动命令
        /// </summary>
        private void SendMeasurementStartCommand()
        {
            Console.WriteLine("[命令] 发送测量启动命令");
            udpSender.SendRestartRequest(true);
        }

        /// <summary>
        /// 发送轮次停止命令
        /// </summary>
        private void SendRoundStopCommand()
        {
            try
            {
                Console.WriteLine("[命令] 发送轮次停止命令");
                udpSender.SendStopRequest(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[命令错误] 发送停止命令失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 等待轮次数据处理完成
        /// </summary>
        private async Task WaitForRoundDataComplete()
        {
            Console.WriteLine("[等待] 等待轮次数据处理完成");

            const int checkInterval = 100;
            int elapsed = 0;

            while (elapsed < DATA_PROCESSING_TIMEOUT)
            {
                cancellationTokenSource.Token.ThrowIfCancellationRequested();

                if (parser != null)
                {
                    try
                    {
                        var voltagePoints = parser.GetVoltagePoints();
                        await Task.Delay(checkInterval);
                        var voltagePoints2 = parser.GetVoltagePoints();

                        if (voltagePoints.Count == voltagePoints2.Count)
                        {
                            Console.WriteLine("[等待] 轮次数据处理趋于稳定");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"[等待警告] 检查数据处理状态异常: {ex.Message}");
                        break;
                    }
                }

                await Task.Delay(checkInterval);
                elapsed += checkInterval;
            }

            Console.WriteLine("[警告] 轮次数据处理等待超时或异常");
        }

        /// <summary>
        /// 处理所有轮次完成
        /// </summary>
        private async Task HandleAllRoundsCompleted(int totalCount)
        {
            Console.WriteLine($"[完成] 所有 {totalCount} 轮测量已完成");

            UpdateUI(() => {
                lblStatus.Text = "状态: 全部完成";
                lblResult.Text = $"共完成{totalCount}轮测量";
                lblRemaining.Text = "剩余: 全部完成";
            });

            await Task.Delay(3000, cancellationTokenSource.Token);
            ResetUIDisplay();
        }

        /// <summary>
        /// 模拟测量过程 - 支持取消
        /// </summary>
        private async Task WaitForMeasurementCompletion(int timeInMinutes, CancellationToken cancellationToken)
        {
            int totalSeconds = timeInMinutes * 60;

            for (int second = 0; second < totalSeconds; second++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Task.Delay(1000, cancellationToken);

                if (second % 30 == 0 && second > 0)
                {
                    System.Diagnostics.Debug.WriteLine($"测量进度: {second}/{totalSeconds} 秒");
                }
            }
        }

        #endregion

        #endregion

        #region 测量停止控制

        /// <summary>
        /// 停止测量按钮点击事件
        /// </summary>
        private async void btnStopMeasurement_Click(object sender, EventArgs e)
        {
            if (!isMeasurementRunning || cancellationTokenSource == null)
                return;

            if (!UIMessageBox.ShowAsk("确定要停止当前测量吗？\n停止后将无法恢复当前进度。"))
                return;

            await InitiateStopMeasurement();
        }

        /// <summary>
        /// 启动停止测量流程
        /// </summary>
        private async Task InitiateStopMeasurement()
        {
            try
            {
                Console.WriteLine("[用户停止] 开始停止流程");

                UpdateUI(() => {
                    SetStopButtonState(false, "停止中...");
                    lblStatus.Text = "状态: 停止中";
                    lblResult.Text = "正在安全停止系统...";
                });

                await SendStopCommandAndCancel();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[停止错误] {ex.Message}");
                UpdateUI(() => SetStopButtonState(true));
            }
        }

        /// <summary>
        /// 发送停止命令并取消测量
        /// </summary>
        private async Task SendStopCommandAndCancel()
        {
            udpSender.SendStopRequest(true);
            countdownTimer?.Stop();
            cancellationTokenSource?.Cancel();
            await Task.Delay(50);
        }

        #endregion

        #region 错误处理

        /// <summary>
        /// 处理测量被取消的情况
        /// </summary>
        private void HandleMeasurementCancelled()
        {
            Console.WriteLine("[取消] 测量被用户取消");

            try
            {
                udpSender?.SendStopRequest(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[错误] 发送停止命令失败: {ex.Message}");
            }

            UpdateUI(() => {
                lblStatus.Text = "状态: 已停止";
                lblResult.Text = "测量被用户停止";
                lblRemaining.Text = "剩余: 已停止";
                lblCount.Text = "次数: 已停止";
            });
        }

        /// <summary>
        /// 处理测量过程中的错误
        /// </summary>
        private void HandleMeasurementError(Exception ex)
        {
            Console.WriteLine($"[错误] 测量过程发生错误: {ex.Message}");

            UpdateUI(() => {
                lblStatus.Text = "状态: 错误";
                lblResult.Text = "测量发生错误，请检查系统";
                lblRemaining.Text = "剩余: 错误停止";
            });
        }

        #endregion

        #region 资源清理

        /// <summary>
        /// 清理测量相关资源
        /// </summary>
        private async Task CleanupMeasurement()
        {
            Console.WriteLine("[清理] 开始清理测量资源");

            try
            {
                CleanupCalculationSystem();
                RestoreUIState();
                await GracefulShutdown();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[清理错误] {ex.Message}");
                ForceCleanup();
            }

            Console.WriteLine("[清理] 测量资源清理完成");
        }

        /// <summary>
        /// 恢复UI状态
        /// </summary>
        private void RestoreUIState()
        {
            isMeasurementRunning = false;
            SetMeasurementButtonsEnabled(true);
            SetStopButtonState(false);
        }

        /// <summary>
        /// 优雅停止系统组件
        /// </summary>
        private async Task GracefulShutdown()
        {
            Console.WriteLine("[停止] 开始优雅停止系统");

            using (var timeoutCts = new CancellationTokenSource(5000))
            {
                try
                {
                    await StopComponentsInOrder(timeoutCts.Token);
                }
                catch (OperationCanceledException) when (timeoutCts.Token.IsCancellationRequested)
                {
                    Console.WriteLine("[警告] 优雅停止超时，执行强制停止");
                    ForceShutdown();
                }
                finally
                {
                    DisposeAllResources();
                }
            }
        }

        /// <summary>
        /// 按顺序停止各个组件 - 修改版
        /// </summary>
        private async Task StopComponentsInOrder(CancellationToken cancellationToken)
        {
            if (udpReceiver != null)
            {
                Console.WriteLine("[停止] UDP接收器");
                try
                {
                    udpReceiver.Stop();
                    await Task.Delay(100, cancellationToken);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[停止警告] UDP接收器停止异常: {ex.Message}");
                }
            }

            if (parser != null)
            {
                Console.WriteLine("[停止] 等待解析器处理完成");
                await WaitForParserToFinish(cancellationToken);
                parser.Stop();
                await Task.Delay(1000, cancellationToken);
            }

            if (ucCenterView != null)
            {
                Console.WriteLine("[停止] 显示面板");
                UpdateUI(() => ucCenterView.StopPlotPanel());
            }
        }

        /// <summary>
        /// 等待解析器处理完成
        /// </summary>
        private async Task WaitForParserToFinish(CancellationToken cancellationToken)
        {
            const int maxWaitTime = 2000;
            const int checkInterval = 50;
            int elapsed = 0;

            while (elapsed < maxWaitTime && !cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var voltagePoints = parser.GetVoltagePoints();
                    if (voltagePoints.Count == 0)
                    {
                        await Task.Delay(checkInterval, cancellationToken);
                        var voltagePoints2 = parser.GetVoltagePoints();
                        if (voltagePoints2.Count == 0)
                        {
                            Console.WriteLine("[等待] 解析器数据处理完成");
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[等待警告] 检查解析器状态异常: {ex.Message}");
                    break;
                }

                await Task.Delay(checkInterval, cancellationToken);
                elapsed += checkInterval;
            }

            Console.WriteLine("[警告] 解析器数据处理等待超时");
        }

        /// <summary>
        /// 强制停止所有组件
        /// </summary>
        private void ForceShutdown()
        {
            Console.WriteLine("[强制停止] 立即终止所有组件");
            try { udpReceiver?.Stop(); } catch { }
            try { parser?.Stop(); } catch { }
            try { UpdateUI(() => ucCenterView?.StopPlotPanel()); } catch { }
        }

        /// <summary>
        /// 释放所有资源
        /// </summary>
        private void DisposeAllResources()
        {
            try
            {
                Console.WriteLine("[清理] 释放所有资源");

                udpReceiver?.Dispose();
                udpReceiver = null;

                parser?.Dispose();
                parser = null;

                cancellationTokenSource?.Dispose();
                cancellationTokenSource = null;

                Console.WriteLine("[清理] 所有资源已释放");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[清理错误] 资源释放失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 强制清理资源（异常情况下使用）
        /// </summary>
        private void ForceCleanup()
        {
            try { DisposeAllResources(); } catch { }
            try { RestoreUIState(); } catch { }
        }

        #endregion

        #region 计算相关方法

        /// <summary>
        /// 获取测量参数
        /// </summary>
        private MeasurementParameters GetMeasurementParameters(string measurementType)
        {
            try
            {
                var parameters = MeasurementCalculatorFactory.CreateDefaultParameters(measurementType);

                if (parameters == null)
                {
                    Console.WriteLine($"[参数] {measurementType} 不需要特殊参数");
                    return null;
                }

                // 根据测量类型从相应的用户控件获取参数
                UpdateParametersFromControls(measurementType, parameters);

                Console.WriteLine($"[参数] {measurementType} 参数获取完成");
                return parameters;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[参数错误] 获取 {measurementType} 参数失败: {ex.Message}");
                return MeasurementCalculatorFactory.CreateDefaultParameters(measurementType);
            }
        }

        /// <summary>
        /// 从用户控件更新参数
        /// </summary>
        private void UpdateParametersFromControls(string measurementType, MeasurementParameters parameters)
        {
            switch (measurementType)
            {
                case "WorkingSourceEfficiency":
                    if (parameters is WorkingSourceParameters workParams)
                    {
                        UpdateWorkingSourceParameters(workParams);
                    }
                    break;

                case "StandardSourceEfficiency":
                    if (parameters is StandardSourceParameters stdParams)
                    {
                        UpdateStandardSourceParameters(stdParams);
                    }
                    break;

                case "WaterSample":
                    if (parameters is WaterSampleParameters waterParams)
                    {
                        UpdateWaterSampleParameters(waterParams);
                    }
                    break;

                case "BioSample":
                    if (parameters is BioSampleParameters bioParams)
                    {
                        UpdateBioSampleParameters(bioParams);
                    }
                    break;

                case "GasSample":
                    if (parameters is GasSampleParameters gasParams)
                    {
                        UpdateGasSampleParameters(gasParams);
                    }
                    break;

                case "EnvSample":
                    if (parameters is EnvSampleParameters envParams)
                    {
                        UpdateEnvSampleParameters(envParams);
                    }
                    break;
            }
        }

        /// <summary>
        /// 更新工作源效率参数
        /// </summary>
        private void UpdateWorkingSourceParameters(WorkingSourceParameters parameters)
        {
            try
            {
                ucEfficiencyMeasurement?.RefreshPresetData();

                if (ucEfficiencyMeasurement != null)
                {
                    parameters.GeometryFactor = ucEfficiencyMeasurement.GetGeometryFactor();

                    double[] alphaEmissions = ucEfficiencyMeasurement.GetAllAlphaSurfaceEmissions();
                    double[] betaEmissions = ucEfficiencyMeasurement.GetAllBetaSurfaceEmissions();

                    UpdateEmissionRates(parameters, alphaEmissions, betaEmissions);
                }
                else
                {
                    UseDefaultWorkingSourceParameters(parameters);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新工作源参数失败: {ex.Message}");
                UseDefaultWorkingSourceParameters(parameters);
            }
        }

        /// <summary>
        /// 更新发射率数组
        /// </summary>
        private void UpdateEmissionRates(WorkingSourceParameters parameters, double[] alphaEmissions, double[] betaEmissions)
        {
            for (int i = 0; i < channelCount; i++)
            {
                parameters.AlphaEmissionRates[i] = i < alphaEmissions.Length ? alphaEmissions[i] : 1440;
                parameters.BetaEmissionRates[i] = i < betaEmissions.Length ? betaEmissions[i] : 1594;
            }
        }

        /// <summary>
        /// 使用默认工作源参数
        /// </summary>
        private void UseDefaultWorkingSourceParameters(WorkingSourceParameters parameters)
        {
            for (int i = 0; i < channelCount; i++)
            {
                parameters.AlphaEmissionRates[i] = 1440;
                parameters.BetaEmissionRates[i] = 1594;
            }
            parameters.GeometryFactor = 0.9;
        }

        /// <summary>
        /// 更新标准源效率参数
        /// </summary>
        private void UpdateStandardSourceParameters(StandardSourceParameters parameters)
        {
            try
            {
                ucStandardSource?.RefreshPresetData();

                if (ucStandardSource != null)
                {
                    double[] alphaActivities = ucStandardSource.GetAllAlphaSpecificActivities();
                    double[] betaActivities = ucStandardSource.GetAllBetaSpecificActivities();
                    double[] sourceMasses = ucStandardSource.GetAllAverageSourceMasses();

                    UpdateStandardSourceArrays(parameters, alphaActivities, betaActivities, sourceMasses);
                }
                else
                {
                    UseDefaultStandardSourceParameters(parameters);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新标准源参数失败: {ex.Message}");
                UseDefaultStandardSourceParameters(parameters);
            }
        }

        /// <summary>
        /// 更新标准源参数数组
        /// </summary>
        private void UpdateStandardSourceArrays(StandardSourceParameters parameters,
            double[] alphaActivities, double[] betaActivities, double[] sourceMasses)
        {
            for (int i = 0; i < channelCount; i++)
            {
                parameters.AlphaSpecificActivity[i] = i < alphaActivities.Length ? alphaActivities[i] : 12.5;
                parameters.BetaSpecificActivity[i] = i < betaActivities.Length ? betaActivities[i] : 14.4;
                parameters.SourceMass[i] = i < sourceMasses.Length ? sourceMasses[i] : parameters.GetRecommendedSourceMass();
            }
        }

        /// <summary>
        /// 使用默认标准源参数
        /// </summary>
        private void UseDefaultStandardSourceParameters(StandardSourceParameters parameters)
        {
            for (int i = 0; i < channelCount; i++)
            {
                parameters.AlphaSpecificActivity[i] = 12.5;
                parameters.BetaSpecificActivity[i] = 14.4;
                parameters.SourceMass[i] = parameters.GetRecommendedSourceMass();
            }
        }

        /// <summary>
        /// 更新水样品参数
        /// </summary>
        private void UpdateWaterSampleParameters(WaterSampleParameters parameters)
        {
            try
            {
                parameters.WaterVolume = ucWaterSampleCheck.GetWaterVolume();
                parameters.TotalResidueAmount = ucWaterSampleCheck.GetTotalResidue();
                parameters.TestedSampleMass = ucWaterSampleCheck.GetTestedSampleMass();
                parameters.UseStandardEfficiency = ucWaterSampleCheck.GetUseStandardEfficiency();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[参数警告] 获取水样品参数失败，使用默认值: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新生物样品参数
        /// </summary>
        private void UpdateBioSampleParameters(BioSampleParameters parameters)
        {
            try
            {
                parameters.FreshSampleWeight = ucBioSamoleCheck.GetFreshSampleWeight();
                parameters.TestedSampleMass = ucBioSamoleCheck.GetTestedSampleMass();
                parameters.TotalAshWeight = ucBioSamoleCheck.GetTotalAshWeight();
                parameters.RecoveryRate = ucBioSamoleCheck.GetRecoveryRate();
                parameters.UseStandardEfficiency = ucBioSamoleCheck.GetUseStandardEfficiency();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[参数警告] 获取生物样品参数失败，使用默认值: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新气体样品参数
        /// </summary>
        private void UpdateGasSampleParameters(GasSampleParameters parameters)
        {
            try
            {
                parameters.SamplingVolume = ucGasSampleCheck.GetSamplingVolume();
                parameters.FilterEfficiency = ucGasSampleCheck.GetFilterEfficiency();
                parameters.AbsorptionFactor = ucGasSampleCheck.GetAbsorptionFactor();
                parameters.UseStandardEfficiency = ucGasSampleCheck.GetUseStandardEfficiency();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[参数警告] 获取气体样品参数失败，使用默认值: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新环境样品参数
        /// </summary>
        private void UpdateEnvSampleParameters(EnvSampleParameters parameters)
        {
            try
            {
                parameters.TestedSampleMass = ucEnvSampleCheck.GetTestedSampleMass();
                parameters.CorrectionFactor = ucEnvSampleCheck.GetCorrectionFactor();
                parameters.UseStandardEfficiency = ucEnvSampleCheck.GetUseStandardEfficiency();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[参数警告] 获取环境样品参数失败，使用默认值: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前轮次的实际点数 - 修正版本
        /// </summary>
        private Dictionary<int, (long actualAlpha, long actualBeta, long deducted)> GetActualCountsForRound(
            Dictionary<int, RealtimeStatisticsData> currentStats) // 修正类型
        {
            var result = new Dictionary<int, (long actualAlpha, long actualBeta, long deducted)>();

            try
            {
                var selectedChannels = ChannelDataManager.GetSelectedChannels();

                foreach (var channelData in selectedChannels)
                {
                    int channelIndex = channelData.ChannelIndex;

                    if (currentStats.ContainsKey(channelIndex))
                    {
                        var stats = currentStats[channelIndex];

                        long actualAlpha = stats.TotalAlphaPoints;
                        long actualBeta = stats.TotalBetaPoints;
                        long deducted = stats.TotalDeductedPoints;

                        // 如果有轮次基准数据，计算本轮增量
                        if (roundBaselineStats.ContainsKey(channelIndex))
                        {
                            var baseline = roundBaselineStats[channelIndex];
                            actualAlpha -= baseline.AlphaPoints;
                            actualBeta -= baseline.BetaPoints;
                            deducted -= baseline.DeductedPoints;
                        }

                        result[channelIndex] = (actualAlpha, actualBeta, deducted);

                        Console.WriteLine($"[实际点数] 通道 {channelIndex + 1}: " +
                            $"α={actualAlpha}, β={actualBeta}, 扣除={deducted}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[实际点数错误] 获取实际点数失败: {ex.Message}");
            }

            return result;
        }
        /// <summary>
        /// 从当前轮次收集测量数据并执行计算 - 修正版本
        /// </summary>
        /// <summary>
        /// 从当前轮次收集测量数据 - 统一数据源版本
        /// </summary>
        private async Task CollectMeasurementDataFromCurrentRound(int currentRound)
        {
            try
            {
                Console.WriteLine($"[收集] 开始收集第 {currentRound} 轮数据");
                await Task.Delay(500);

                // 使用与UcCenterView相同的数据源
                var currentStats = ChannelDataManager.GetAllChannelStatistics();
                var actualCounts = GetActualCountsForRound(currentStats);

                // 将实际点数转换为计数率（用于计算器）
                var roundData = ConvertCountsToRates(actualCounts);

                if (roundData.Count > 0 && actualCounts.Count > 0)
                {
                    // 继续现有的处理逻辑...
                    foreach (var kvp in roundData)
                    {
                        int channelIndex = kvp.Key;
                        double alpha = kvp.Value.Item1;
                        double beta = kvp.Value.Item2;

                        if (measurementHistory.ContainsKey(channelIndex))
                        {
                            measurementHistory[channelIndex].Add((alpha, beta));
                            Console.WriteLine($"[数据] 通道 {channelIndex + 1}: α={alpha:F6}, β={beta:F6} (转换自实际点数)");
                        }
                    }

                    // 计算当前轮次结果
                    calculationContext.RawData = roundData;
                    calculationContext.CurrentRound = currentRound;

                    if (currentCalculator != null)
                    {
                        var result = await currentCalculator.CalculateAsync(calculationContext);
                        if (result.IsSuccess)
                        {
                            StoreCurrentRoundResults(currentRound, roundData, result, actualCounts);
                            DisplayCalculationSummary(result, currentRound);
                            if (currentRound == calculationContext.TotalRounds)
                            {
                                await ProcessFinalResults();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[收集错误] 第 {currentRound} 轮数据收集失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 将实际点数转换为计数率 - 新增方法
        /// </summary>
        private Dictionary<int, (double alpha, double beta)> ConvertCountsToRates(
            Dictionary<int, (long actualAlpha, long actualBeta, long deducted)> actualCounts)
        {
            var result = new Dictionary<int, (double alpha, double beta)>();
            int measurementSeconds = measurementTime * 60;

            foreach (var kvp in actualCounts)
            {
                int channelIndex = kvp.Key;
                var counts = kvp.Value;

                // 将点数转换为计数率
                double alphaRate = measurementSeconds > 0 ? counts.actualAlpha / (double)measurementSeconds : 0;
                double betaRate = measurementSeconds > 0 ? counts.actualBeta / (double)measurementSeconds : 0;

                result[channelIndex] = (alphaRate, betaRate);

                Console.WriteLine($"[转换] 通道 {channelIndex + 1}: " +
                    $"实际点数(α:{counts.actualAlpha}, β:{counts.actualBeta}) → " +
                    $"计数率(α:{alphaRate:F6}/s, β:{betaRate:F6}/s)");
            }

            return result;
        }
        /// <summary>
        /// 存储当前轮次结果 - 新增方法
        /// </summary>
        /// <summary>
        /// 存储当前轮次结果 - 包含点数信息
        /// </summary>
        /// <summary>
        /// 存储当前轮次结果 - 包含点数信息
        /// </summary>
        /// <summary>
        /// 存储当前轮次结果 - 使用实际统计点数
        /// </summary>
        private void StoreCurrentRoundResults(int currentRound,
            Dictionary<int, (double alphaRate, double betaRate)> roundData,
            MeasurementCalculationResult result,
            Dictionary<int, (long actualAlpha, long actualBeta, long deducted)> actualCounts) // 新增参数
        {
            try
            {
                foreach (var kvp in roundData)
                {
                    int channelIndex = kvp.Key;
                    double alphaCountRate = kvp.Value.alphaRate;
                    double betaCountRate = kvp.Value.betaRate;

                    if (result.ChannelResults.ContainsKey(channelIndex) &&
                        channelRoundResults.ContainsKey(channelIndex) &&
                        actualCounts.ContainsKey(channelIndex)) // 确保有实际点数数据
                    {
                        var channelResult = result.ChannelResults[channelIndex];
                        var actualCount = actualCounts[channelIndex];

                        var roundResult = new RoundResult
                        {
                            RoundNumber = currentRound,
                            AlphaCountRate = alphaCountRate,
                            BetaCountRate = betaCountRate,
                            AlphaResult = channelResult.AlphaResult,
                            BetaResult = channelResult.BetaResult,
                            Timestamp = DateTime.Now,
                            // 直接使用实际统计的点数，不再计算
                            AlphaTotalCounts = actualCount.actualAlpha,
                            BetaTotalCounts = actualCount.actualBeta,
                            DeductedTotalCounts = actualCount.deducted,
                            MeasurementDurationSeconds = measurementTime * 60
                        };

                        channelRoundResults[channelIndex].Add(roundResult);
                        currentMultiRoundData.ChannelResults[channelIndex].RoundResults.Add(roundResult);

                        Console.WriteLine($"[存储] 通道 {channelIndex + 1} 第 {currentRound} 轮结果已存储 " +
                            $"(实际α点数:{actualCount.actualAlpha}, 实际β点数:{actualCount.actualBeta}, 扣除点数:{actualCount.deducted})");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[存储错误] 存储第 {currentRound} 轮结果失败: {ex.Message}");
            }
        }
        /// <summary>
                /// 计算平均结果和统计信息 - 新增方法
                /// </summary>
        private void CalculateAverageResults()
        {
            foreach (var kvp in channelRoundResults)
            {
                int channelIndex = kvp.Key;
                var roundResults = kvp.Value;

                if (roundResults.Count > 0)
                {
                    // 计算平均值
                    var avgAlphaCountRate = roundResults.Average(r => r.AlphaCountRate);
                    var avgBetaCountRate = roundResults.Average(r => r.BetaCountRate);
                    var avgAlphaResult = roundResults.Average(r => r.AlphaResult);
                    var avgBetaResult = roundResults.Average(r => r.BetaResult);

                    //// 计算标准差
                    //var alphaResults = roundResults.Select(r => r.AlphaResult).ToArray();
                    //var betaResults = roundResults.Select(r => r.BetaResult).ToArray();

                    //var alphaStdDev = CalculateStandardDeviation(alphaResults, avgAlphaResult);
                    //var betaStdDev = CalculateStandardDeviation(betaResults, avgBetaResult);

                    //// 计算相对误差 (%)
                    //var alphaRelativeError = avgAlphaResult != 0 ? (alphaStdDev / avgAlphaResult) * 100 : 0;
                    //var betaRelativeError = avgBetaResult != 0 ? (betaStdDev / avgBetaResult) * 100 : 0;

                    //// 计算95%置信区间
                    //var alphaCI = CalculateConfidenceInterval(alphaResults, avgAlphaResult, alphaStdDev);
                    //var betaCI = CalculateConfidenceInterval(betaResults, avgBetaResult, betaStdDev);

                    // 存储平均结果
                    currentMultiRoundData.ChannelResults[channelIndex].AverageResult = new RoundResult
                    {
                        RoundNumber = -1, // 表示平均结果
                        AlphaCountRate = avgAlphaCountRate,
                        BetaCountRate = avgBetaCountRate,
                        AlphaResult = avgAlphaResult,
                        BetaResult = avgBetaResult,
                        Timestamp = DateTime.Now
                    };

                    // 存储统计信息
                    //currentMultiRoundData.ChannelResults[channelIndex].Statistics = new MeasurementStatistics
                    //{
                    //    AlphaStandardDeviation = alphaStdDev,
                    //    BetaStandardDeviation = betaStdDev,
                    //    AlphaRelativeError = alphaRelativeError,
                    //    BetaRelativeError = betaRelativeError,
                    //    AlphaConfidenceInterval = alphaCI,
                    //    BetaConfidenceInterval = betaCI
                    //};

                    //Console.WriteLine($"[平均计算] 通道 {channelIndex + 1}: α平均={avgAlphaResult:F6}±{alphaStdDev:F6}, β平均={avgBetaResult:F6}±{betaStdDev:F6}");
                }
            }
        }

        /// <summary>
        /// 计算标准差 - 新增方法
        /// </summary>
        private double CalculateStandardDeviation(double[] values, double mean)
        {
            if (values.Length <= 1) return 0;

            var sumOfSquaredDifferences = values.Sum(v => Math.Pow(v - mean, 2));
            return Math.Sqrt(sumOfSquaredDifferences / (values.Length - 1));
        }

        /// <summary>
        /// 计算95%置信区间 - 新增方法
        /// </summary>
        private (double Lower, double Upper) CalculateConfidenceInterval(double[] values, double mean, double stdDev)
        {
            if (values.Length <= 1) return (mean, mean);

            // 95% 置信区间，t值近似为1.96（当样本数较大时）
            var tValue = values.Length > 30 ? 1.96 : GetTValue(values.Length - 1);
            var marginOfError = tValue * (stdDev / Math.Sqrt(values.Length));

            return (mean - marginOfError, mean + marginOfError);
        }

        /// <summary>
        /// 获取t值（简化版本） - 新增方法
        /// </summary>
        private double GetTValue(int degreesOfFreedom)
        {
            // 简化的t值表，实际应用中可以使用更精确的计算
            if (degreesOfFreedom >= 30) return 1.96;
            if (degreesOfFreedom >= 10) return 2.23;
            if (degreesOfFreedom >= 5) return 2.57;
            return 3.18; // df = 1-4
        }

        /// <summary>
        /// 创建最终计算结果 - 新增方法
        /// </summary>
        private MeasurementCalculationResult CreateFinalCalculationResult()
        {
            var finalResult = new MeasurementCalculationResult
            {
                MeasurementType = currentMultiRoundData.MeasurementType,
                IsSuccess = true,
                IsFinalResult = true,
                CalculationTime = DateTime.Now
            };

            foreach (var kvp in currentMultiRoundData.ChannelResults)
            {
                var channelIndex = kvp.Key;
                var channelData = kvp.Value;
                var avgResult = channelData.AverageResult;

                if (avgResult != null)
                {
                    // 这里需要根据实际的ChannelCalculationResult结构调整
                    // 假设存在这样的构造函数或属性设置方式
                    finalResult.ChannelResults[channelIndex] = new ChannelCalculationResult
                    {
                        ChannelIndex = channelIndex,
                        AlphaResult = avgResult.AlphaResult,
                        BetaResult = avgResult.BetaResult
                        // 根据实际需要添加其他属性
                    };
                }
            }

            return finalResult;
        }

        /// <summary>
        /// 显示计算结果摘要
        /// </summary>
        private void DisplayCalculationSummary(MeasurementCalculationResult result, int currentRound)
        {
            try
            {
                var summary = $"第{currentRound}轮 {result.MeasurementType}";
                if (result.ChannelResults.Count > 0)
                {
                    var firstChannel = result.ChannelResults.First().Value;
                    summary += $" α:{firstChannel.AlphaResult:F4} β:{firstChannel.BetaResult:F4}";
                }

                UpdateUI(() => lblResult.Text = summary);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[显示错误] 无法显示计算摘要: {ex.Message}");
            }
        }

        /// <summary>
        /// 显示最终结果 - 修改版本，支持详细结果窗口
        /// </summary>
        private void DisplayFinalResults(MeasurementCalculationResult result)
        {
            try
            {
                UpdateUI(() => lblResult.Text = $"{result.MeasurementType} 测量完成，共 {result.ChannelResults.Count} 个通道");

                // 显示简化的成功消息
                var simpleMessage = BuildSimpleCompletionMessage(result);

                Task.Run(() => {
                    UpdateUI(() => {


                        // 如果用户选择了 OK
                        var dialogResult = UIMessageBox.Show(
                            simpleMessage,
                            "测量完成",
                            UIStyle.Green,
                            UIMessageBoxButtons.OKCancel);

                        if (dialogResult)
                        {
                            ShowDetailedResultsWindow();
                        }

                    });
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[显示错误] 无法显示最终结果: {ex.Message}");
            }
        }

        /// <summary>
        /// 构建简化的完成消息 - 新增方法
        /// </summary>
        private string BuildSimpleCompletionMessage(MeasurementCalculationResult result)
        {
            var message = $"{result.MeasurementType} 多轮测量完成！\n\n";
            message += $"总轮数: {currentMultiRoundData.TotalRounds}\n";
            message += $"参与通道: {result.ChannelResults.Count} 个\n";
            message += $"测量耗时: {(currentMultiRoundData.EndTime - currentMultiRoundData.StartTime).TotalMinutes:F1} 分钟\n\n";

            // 显示平均结果摘要
            message += "平均结果摘要:\n";
            foreach (var channelResult in result.ChannelResults.OrderBy(kvp => kvp.Key).Take(3))
            {
                var channel = channelResult.Value;
                message += $"通道 {channel.ChannelIndex + 1}: α={channel.AlphaResult:F4}, β={channel.BetaResult:F4}\n";
            }

            if (result.ChannelResults.Count > 3)
            {
                message += $"... 还有 {result.ChannelResults.Count - 3} 个通道\n";
            }

            message += "\n数据已保存\n";
            message += "点击 确定 查看详细结果，取消 关闭此对话框";

            return message;
        }

        /// <summary>
        /// 显示详细结果窗口 - 新增方法
        /// </summary>
        private void ShowDetailedResultsWindow()
        {
            try
            {
                if (currentMultiRoundData != null)
                {
                    var detailForm = new MultiRoundResultForm(currentMultiRoundData);
                    detailForm.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"显示详细结果窗口失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 显示详细结果对话框
        /// </summary>
        private void ShowDetailedResults(MeasurementCalculationResult result)
        {
            try
            {
                var message = BuildDetailedResultMessage(result);

                Task.Run(() => {
                    UpdateUI(() => UIMessageBox.ShowSuccess(message));
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[显示错误] 无法显示详细结果: {ex.Message}");
            }
        }

        /// <summary>
        /// 构建详细结果消息
        /// </summary>
        /// <summary>
        /// 构建详细结果消息 - 修改版本
        /// </summary>
        private string BuildDetailedResultMessage(MeasurementCalculationResult result)
        {
            var message = $"{result.MeasurementType} 多轮测量完成！\n";
            message += $"总轮数: {currentMultiRoundData.TotalRounds}\n";
            message += $"每轮测量时间: {currentMultiRoundData.MeasurementTimeMinutes} 分钟\n";
            message += $"总测量时间: {(currentMultiRoundData.EndTime - currentMultiRoundData.StartTime).TotalMinutes:F1} 分钟\n";
            message += $"测量时间: {currentMultiRoundData.StartTime:yyyy-MM-dd HH:mm} - {currentMultiRoundData.EndTime:yyyy-MM-dd HH:mm}\n\n";

            // 添加每轮详细结果
            message += BuildRoundByRoundResults();

            // 添加平均结果和统计信息
            message += BuildAverageResultsAndStatistics(result);

            message += $"\n数据已保存到JSON文件: {GetJsonFileName()}\n";
            return message;
        }

        /// <summary>
        /// 获取JSON文件名 - 新增方法
        /// </summary>
        private string GetJsonFileName()
        {
            return $"{currentMultiRoundData.MeasurementType}_{currentMultiRoundData.StartTime:yyyyMMdd_HHmmss}_{currentMultiRoundData.MeasurementId}.json";
        }

        /// <summary>
        /// 构建平均结果和统计信息 - 新增方法
        /// </summary>
        private string BuildAverageResultsAndStatistics(MeasurementCalculationResult result)
        {
            var message = "【平均结果与统计分析】\n";

            foreach (var channelResult in result.ChannelResults.OrderBy(kvp => kvp.Key))
            {
                var channel = channelResult.Value;
                var channelIndex = channel.ChannelIndex;

                if (currentMultiRoundData.ChannelResults.ContainsKey(channelIndex))
                {
                    var channelData = currentMultiRoundData.ChannelResults[channelIndex];
                    var statistics = channelData.Statistics;
                    var avgResult = channelData.AverageResult;

                    message += $"通道 {channelIndex + 1}:\n";
                    message += $"  α平均值: {channel.AlphaResult:F6} ± {statistics?.AlphaStandardDeviation:F6}\n";
                    message += $"  β平均值: {channel.BetaResult:F6} ± {statistics?.BetaStandardDeviation:F6}\n";
                    message += $"  α相对误差: {statistics?.AlphaRelativeError:F2}%\n";
                    message += $"  β相对误差: {statistics?.BetaRelativeError:F2}%\n";

                    if (statistics != null)
                    {
                        message += $"  α置信区间(95%): [{statistics.AlphaConfidenceInterval.Lower:F6}, {statistics.AlphaConfidenceInterval.Upper:F6}]\n";
                        message += $"  β置信区间(95%): [{statistics.BetaConfidenceInterval.Lower:F6}, {statistics.BetaConfidenceInterval.Upper:F6}]\n";
                    }

                    if (avgResult != null)
                    {
                        message += $"  α平均计数率: {avgResult.AlphaCountRate:F3}/s\n";
                        message += $"  β平均计数率: {avgResult.BetaCountRate:F3}/s\n";
                    }
                    message += "\n";
                }
            }

            return message;
        }


        /// <summary>
        /// 构建逐轮结果详情 - 新增方法
        /// </summary>
        private string BuildRoundByRoundResults()
        {
            var message = "【各轮测量结果】\n";

            // 获取所有通道索引并排序
            var channelIndices = currentMultiRoundData.ChannelResults.Keys.OrderBy(k => k).ToList();

            if (channelIndices.Count == 0)
            {
                return message + "暂无数据\n\n";
            }

            // 按轮次展示结果
            for (int round = 1; round <= currentMultiRoundData.TotalRounds; round++)
            {
                message += $"第 {round} 轮:\n";

                foreach (var channelIndex in channelIndices)
                {
                    var channelData = currentMultiRoundData.ChannelResults[channelIndex];
                    var roundResult = channelData.RoundResults.FirstOrDefault(r => r.RoundNumber == round);

                    if (roundResult != null)
                    {
                        message += $"  通道 {channelIndex + 1}: ";
                        message += $"α={roundResult.AlphaResult:F6} (计数率:{roundResult.AlphaCountRate:F3}/s), ";
                        message += $"β={roundResult.BetaResult:F6} (计数率:{roundResult.BetaCountRate:F3}/s)\n";
                    }
                    else
                    {
                        message += $"  通道 {channelIndex + 1}: 数据缺失\n";
                    }
                }
                message += "\n";
            }

            return message;
        }


        /// <summary>
        /// 从解析器提取测量数据
        /// </summary>
        private Dictionary<int, (double alpha, double beta)> ExtractDataFromParser()
        {
            var result = new Dictionary<int, (double alpha, double beta)>();

            try
            {
                if (parser == null)
                {
                    Console.WriteLine("[提取错误] 解析器为空");
                    return result;
                }

                var selectedChannels = ChannelDataManager.GetSelectedChannels();

                foreach (var channelData in selectedChannels)
                {
                    int channelIndex = channelData.ChannelIndex;

                    try
                    {
                        if (TryGetCountRatesFromStatistics(channelIndex, out double alphaRate, out double betaRate))
                        {
                            result[channelIndex] = (alphaRate, betaRate);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"[提取警告] 通道 {channelIndex + 1} 数据处理失败: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[提取错误] 提取数据失败: {ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 从统计数据获取计数率
        /// </summary>
        private bool TryGetCountRatesFromStatistics(int channelIndex, out double alphaRate, out double betaRate)
        {
            alphaRate = 0;
            betaRate = 0;

            try
            {
                var statistics = ChannelDataManager.GetChannelStatistics(channelIndex);
                if (statistics != null)
                {
                    alphaRate = statistics.AlphaCountsPerSecond;
                    betaRate = statistics.BetaCountsPerSecond;
                    return alphaRate > 0 || betaRate > 0;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 清理计算系统
        /// </summary>
        private void CleanupCalculationSystem()
        {
            try
            {
                measurementHistory.Clear();
                currentCalculator = null;
                calculationContext = null;
                Console.WriteLine("[清理] 计算系统已重置");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[清理错误] 计算系统清理失败: {ex.Message}");
            }
        }

        #endregion

        #region 静态方法与资源释放

        /// <summary>
        /// 获取UDP发送器实例（静态方法）
        /// </summary>
        internal static UdpProtocolSender getUdpSender()
        {
            return udpSender;
        }

        /// <summary>
        /// 释放窗体资源
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                udpSender?.Dispose();
                if (components != null)
                    components.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion
    }
}